﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SalesSys.BLL;
using SalesSys.BLL.Depot;
using SalesSys.Comm.Utility;
using SalesSys.DAL.Models;
using SalesSys.Service.Purchasing;
using SalesSys.WebCore;
using SalesSys.WebCore.Authorize;
using System.IO;
using hlib.IO;
using SalesSys.Comm.BLL;
using System.Linq;

namespace SalesSys.Site.Controllers.Api
{
    /// <summary>
    /// 采购单
    /// </summary>
    [RoutePrefix("api/Purchase")]
    public class PurchaseController : BaseApiController
    {
        private IDepotBLL depotBLL = new DepotBLL();
        private IPurchasingSvc purchasingSvc = new PurchasingSvc();
        private IBaseBLL<PurchaseOrder, Guid> purchaseOrderBll = new PurchasingSvc();
        private EmployeeBLL employeeBll = new EmployeeBLL();

        /// <summary>
        /// 创建采购单并提交
        /// </summary>
        /// <param name="purchaseOrder">采购单实体</param>
        /// <returns></returns>
        public IResultState Post(PurchaseOrder purchaseOrder)
        {
            if (purchaseOrder.Provider == null || purchaseOrder.Provider.ProviderType == ProviderType.Depot)
            {
                return ReState.ArgError.Create("错误的供应商信息");
            }
            if (purchaseOrder.Goodses == null || purchaseOrder.Goodses.Count < 1)
            {
                return ReState.ArgError.Create("商品信息错误");
            }
            if (purchaseOrder.Provider.Manager == null || purchaseOrder.Provider.MainFieldMan == null)
            {
                return ReState.ArgError.Create("供应商驻厂专员或区域经理未配置，请联系管理员");
            }


            purchaseOrder.Creater = employeeBll.Details(ClientHelper.ClientInfo.Id);
            purchaseOrder.PurchaseType = PurchaseType.Creater;
            return purchasingSvc.Create(purchaseOrder);
        }

        /// <summary>
        /// 采购单入库
        /// </summary>
        /// <param name="purchaseOrderId">采购单编号</param>
        /// <returns></returns>
        [Route("PurchasingEntry")]
        public IResultState PurchasingEntry(Guid purchaseOrderId)
        {
            return purchasingSvc.PurchasingEntry(purchaseOrderId);
        }

        /// <summary>
        /// 修改采购单价格，已入库则设置入库单成本
        /// </summary>
        /// <param name="porder">采购单实体</param>
        /// <returns></returns>
        [Route("SetPurchasingPrice")]
        public IResultState SetPurchasingPrice(PurchaseOrder porder)
        {
            return purchasingSvc.SetPurchasingPrice(ClientHelper.ClientInfo.Id, porder);
        }

        /// <summary>
        /// 修改采购单价格和重量，已入库则设置入库单成本
        /// </summary>
        /// <param name="porder">采购单实体</param>
        /// <returns></returns>
        [Route("SetWeightAndPrice")]
        public IResultState SetWeightAndPrice(PurchaseOrder porder)
        {
            return purchasingSvc.SetWeightAndPrice(ClientHelper.ClientInfo.Id, porder);
        }

        /// <summary>
        /// 直发采购完成
        /// </summary>
        /// <param name="pId">采购单编号</param>
        /// <returns></returns>
        [Route("SalePurchaseComplete")]
        public IResultState SalePurchaseComplete(Guid pId)
        {
            return purchasingSvc.SalePurchaseComplete(ClientHelper.ClientInfo, pId);
        }

        /// <summary>
        /// 直发销售采购单， 
        /// </summary>
        /// <param name="po">采购单实体</param>
        /// <returns></returns>
        [Route("SalePurchaseEdit")]
        public IResultState SalePurchaseEdit(PurchaseOrder po)
        {
            return purchasingSvc.SalePurchaseEdit(ClientHelper.ClientInfo.Id, po);
        }
        /// <summary>
        /// 修改采购单备注及联系人
        /// </summary>
        /// <param name="po">采购单实体</param>
        /// <returns></returns>
        [Route("PurchaseRemarkEdit")]
        public IResultState PurchaseRemarkEdit(PurchaseOrder po)
        {
            var old = purchaseOrderBll.Details(po.Id);
            old.Remarks = po.Remarks;
            old.Contact = po.Contact;
            PurchaseOrder.AddPurchaseRecord(ClientHelper.ClientInfo, old, PurchaseRecordType.Msg, "修改联系人及备注");
            purchaseOrderBll.Edit(old);
            return ReState.Success.Create();
        }

        /// <summary>
        /// 获取采购单列表
        /// </summary>
        /// <param name="name">联系人\创建人名称\供应商名称，模糊查询</param>
        /// <param name="state">采购单状态</param>
        /// <param name="page">分页</param>
        /// <param name="rows">每页条数</param>
        /// <returns></returns>
        public ViewDtos<PurchaseOrder> Get(string name = null, PurchaseOrder.PurchaseState? state = null, int page = 1, int rows = 10)
        {
            var data = purchasingSvc.GetList(name, state, ClientHelper.ClientInfo.Id, page, rows);
            var dto = ViewDto.CreateList(data.Value);
            dto.Total = data.Key;
            dto.Page = page;
            dto.Rows = 10;
            return dto;
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id">采购单详情</param>
        /// <returns></returns>
        public PurchaseOrder Get(Guid id)
        {
            return purchaseOrderBll.Details(id);
        }

        /// <summary>
        /// 通过FromId获取采购单，用于直发查找采购单FromId为计划单Id
        /// </summary>
        /// <param name="fromId">计划单编号</param>
        /// <returns></returns>
        [HttpGet]
        [Route("DetailsByFromId")]
        public PurchaseOrder DetailsByFromId(Guid fromId)
        {
            return purchaseOrderBll.GetList(p => p.FromId == fromId).FirstOrDefault();
        }

        /// <summary>
        /// 设置采购单完成
        /// </summary>
        /// <param name="orderId">采购单编号</param>
        /// <returns></returns>
        [Route("PurchaseComplete")]
        public IResultState PurchaseComplete(Guid orderId)
        {
            return purchasingSvc.PurchaseComplete(ClientHelper.ClientInfo, orderId);

        }


        /// <summary>
        /// 采购导出
        /// </summary>       
        /// <returns></returns>

        [Route("ExpCustomer")]
        [HttpGet]
        public HttpResponseMessage ExpCustomer()
        {
            var data = purchasingSvc.GetList(null, null, null, 1, 19999);
            HttpResponseMessage msg = null;
            var expData =
                data.Value.Select(
                    p =>
                        new string[]
                        {
                            p.Id.ToString(), p.Creater==null?"":p.Creater.Name, p.Account, p.IsStandard.ToString(), p.CreateTime.ToString(),                           
                            p.District==null?null:p.District.Name, p.DeliveryAccount, p.DeliveryPrice.ToString(), p.DeliveryPriceTotal.ToString(),
                            p.IsPublicDelivery.ToString(), p.Contact, p.Remarks, p.Provider==null?"":p.Provider.Name, p.PurchaseType.GetDescription(),
                            p.TotalWeight.ToString(), p.Total.ToString(), p.Refund.ToString(), p.SourceWeight.ToString(), p.SourceTotal.ToString(),
                            p.State.GetDescription(), p.ToDepot==null?"":p.ToDepot.Name, p.IsPause.ToString()
                     
                        });

            var nameArray = new string[] { "id", "创建人", "支付户头", "是否标件", "创建时间", 
                "所在地区", "运费户头", "每吨运费", "总运费", "运费是否公户", "联系人", "备注", "供应商名称", "订单类型", 
                "总重量", "实际价格" , "退款", "原重量", "原价格",
                "订单状态", "收货仓库" , "是否暂停"
            };
            msg = CsvExp("采购数据.csv", expData, nameArray);
            return msg;
        }

        /// <summary>
        /// 取消采购单
        /// </summary>
        /// <param name="id">取消采购单</param>
        [Route("Cancel")]
        [ApiUserRoleAuth(RolesConst.Buyer, RolesConst.Admin)]
        public IResultState Cancel(Guid id)
        {
            var order = purchaseOrderBll.Details(id);
            if (order.Creater.Id != ClientHelper.ClientInfo.Id)
                return ReState.Error.Create("您无权取消该采购单");
            return purchasingSvc.PurchaseCancel(ClientHelper.ClientInfo, id);
        }
    }
}
